package com.hengfoxwolf.ffmpegdemo.defineviews
import android.content.Context
import android.graphics.PixelFormat
import android.util.AttributeSet
import android.util.Log
import android.view.Surface
import android.view.SurfaceView
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.launch
import com.hengfoxwolf.ffmpegdemo.util.VideoPlayer
import kotlinx.coroutines.Dispatchers

class FFVideoView @JvmOverloads constructor(context: Context, attributeSet: AttributeSet? = null) :
    SurfaceView(context, attributeSet), CoroutineScope by MainScope() {

    private val surface: Surface
    private val videoPlayer: VideoPlayer

    init {
        holder.setFormat(PixelFormat.RGBA_8888)
        surface = holder.surface

        videoPlayer = VideoPlayer()
        videoPlayer.init()
        Log.d(TAG, "init {}")
    }

    fun playVideo(videoPath: String) {
        launch(Dispatchers.IO) {
            videoPlayer.play(videoPath, surface)
        }
    }

    fun playPause(playPause: Boolean) {
        launch(Dispatchers.IO) {
            videoPlayer.playPause(playPause)
        }
    }

    fun destroy() {
        surface.release()
        videoPlayer.destroy()
    }

    companion object {
        const val TAG = "FFVideoView"
    }
}